package com.xm.settlement.controller;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;

import com.xm.settlement.commons.base.ApiSQLException;
import com.xm.settlement.commons.base.BaseController;
import com.xm.settlement.commons.result.Result;
import com.xm.settlement.commons.utils.*;
import com.xm.settlement.model.Role;
import com.xm.settlement.model.User;
import com.xm.settlement.model.vo.UserVo;
import com.xm.settlement.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description：用户管理
 * @author：loysen
 * @date：2015/10/1 14:51
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    /**
     * 用户管理页
     *
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/user";
    }

    /**
     * 用户管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(UserVo userVo, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
        if (userVo.getOrganizationId() != null) {
            condition.put("organizationId", userVo.getOrganizationId());
        }
        if (userVo.getCreatedateStart() != null) {
            condition.put("startTime", userVo.getCreatedateStart());
        }
        if (userVo.getCreatedateEnd() != null) {
            condition.put("endTime", userVo.getCreatedateEnd());
        }
        pageInfo.setCondition(condition);
        userService.selectDataGrid(pageInfo);
        return pageInfo;
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/userAdd";
    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(UserVo userVo) {
        try {
        List<User> list = userService.selectByLoginName(userVo);
            if (list != null && !list.isEmpty()) {
                return renderError("用户名已存在!");
            }
            userService.insertByVo(userVo,getShiroUser());
        } catch (InterruptedException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        } catch (ApiSQLException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("添加成功");
    }

    /**
     * 编辑用户页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Long id, Model model) {
        UserVo userVo = userService.selectVoById(id);
        List<Role> rolesList = userVo.getRolesList();
        List<Long> ids = new ArrayList<Long>();
        for (Role role : rolesList) {
            ids.add(role.getId());
        }
        model.addAttribute("roleIds", ids);
        model.addAttribute("user", userVo);
        return "admin/userEdit";
    }

    /**
     * 编辑用户
     *
     * @param userVo
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(UserVo userVo) {
        List<User> list = userService.selectByLoginName(userVo);
/*
        if (list != null && !list.isEmpty()) {
            return renderError("用户名已存在!");
        }
*/

        userService.updateByVo(userVo);
        return renderSuccess("修改成功！");
    }

    /**
     * 修改密码页
     *
     * @return
     */
    @GetMapping("/editPwdPage")
    public String editPwdPage() {
        return "admin/userEditPwd";
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param pwd
     * @return
     */
    @RequestMapping("/editUserPwd")
    @ResponseBody
    public Object editUserPwd(String oldPwd, String pwd) {
        User user = userService.selectById(getUserId());
        if (!user.getPassword().equals(DigestUtils.md5Hex(oldPwd))) {
            return renderError("老密码不正确!");
        }

        userService.updatePwdByUserId(getUserId(), DigestUtils.md5Hex(pwd));
        return renderSuccess("密码修改成功！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        userService.deleteUserById(id);
        return renderSuccess("删除成功！");
    }

    /**
     * 下载模版
     */
    @RequestMapping(value = "/downExcel")
    public void downExcel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");
    }


    /**
     * 打开上传EXCEL页面
     */
    @RequestMapping(value = "/goUploadExcel")
    public String goUploadExcel() throws Exception {

        return "admin/uploadexcel";
    }


    /**
     * Excel导入
     */
    @RequestMapping(value = "/readExcel", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadify(@RequestParam("Filedata") MultipartFile multiFile, HttpServletRequest request) throws ApiSQLException {
        Result result = new Result();
        try {
            userService.insertByteArrayToFile(multiFile, request);
            result.setSuccess(true);
        } catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            result.setMsg("未知异常");
        }

        return result;
    }
}